package session

import (
	"database/sql"
	"gitee.com/zhendliu/sorm/clause"
	"gitee.com/zhendliu/sorm/parser"
	"github.com/pkg/errors"
	"strings"
)

// Delete records with where clause
func (s *Session) Delete() (int64, error) {
	defer s.Clear()
	var (
		tableName string
		err       error
	)
	// 强制性要求，必须要要有where条件
	if Exp, _ := s.clause.Get(clause.WHERE); Exp == "" {
		return 0, errors.New("删除时，强制性要求必须要有where条件")
	}

	table := s.RefTable()

	if table.SubTableFile != "" {
		whereExp, values := s.clause.Get(clause.WHERE)
		if strings.Contains(whereExp, table.SubTableFile) {
			timeIndex := strings.Index(whereExp, table.SubTableFile)
			questionMarks := strings.Count(whereExp[:timeIndex], "?")
			if questionMarks > len(values) {
				return 0, errors.New("获取表名失败")
			}
			tableName, err = s.GetTableFromTableAndSplitFiled(table.Name, values[questionMarks])
			if err != nil {
				return 0, errors.New("获取表名失败")
			}
		} else {
			// 如果没有,包含则要加载全部的表名,仅支持取模的方式
			return 0, errors.New("分表删除时，强制性要求必须包含分表字段")
		}
	} else {
		tableName = table.Name
	}

	result, err := s.deleteTable(tableName)
	if err != nil {
		return 0, errors.Wrap(err, "删除失败")
	}
	return result.RowsAffected()
}

func (s *Session) deleteTable(tableName string) (result sql.Result, err error) {
	tname := parser.GetTableName(tableName)
	db, ok := s.dbs[tname]
	if !ok { // 如果没有找到，就说明没有分表，就用默认的db
		db = s.db
	}

	s.clause.Set(clause.DELETE, tableName)
	sql, vars := s.clause.Build(clause.DELETE, clause.WHERE)
	return s.exec(s.ctx, db.Db, db.Dia, sql, vars)
}
